<?php
//创建WebSocket Server对象，监听0.0.0.0:9502端口
$ws = new Swoole\WebSocket\Server('0.0.0.0', 9501);

//监听WebSocket连接打开事件
$ws->on('Open', function ($ws, $request) {
$ws->push($request->fd, "hello, welcome\n");
});

$table = new Swoole\Table(1024);
$table->column('fd', Swoole\Table::TYPE_INT);
$table->column('sn', Swoole\Table::TYPE_STRING,32);
$table->create();

function do_auto_job($num){
    if ($num>600){
        return 1;
    }else{
        return 0;
    }
}

function back_format($data)
{
    return json_encode($data);
}

function get_fd(Swoole\Table $table,$sn)
{
    $fd = $table->get('sn_'.$sn);
    if ($fd)$fd = $fd['fd'];
    return $fd;
}

function saveLink(Swoole\Table $table,$sn,$fd)
{
    $table->set('sn_'.$sn,['fd'=>$fd,'sn'=>$sn]);
    $table->set('fd_'.$fd,['fd'=>$fd,'sn'=>$sn]);
}

/**
 * 连接 {"type":1,"sn":"a123456"}
 * 上传数据 {"type":2,"data":700,"sn":"a123456"}
 * 后台控制 {"type":3,"status":1,"sn":"a123456"}
 * 后台设置 {"type":4,"freq":1000,"sn":"a123456","hand_delay":30000}
 */

//监听WebSocket消息事件
$ws->on('Message', function ($ws, $frame) use($table){
    $arr = json_decode($frame->data,true);
    if ($arr && $arr['type']){
        switch ($arr['type']){
            case 1: //注册设备连接
                saveLink($table,$arr['sn'],$frame->fd);
                break;
            case 2: //接收传感器数据
                if(!get_fd($table,$arr['sn'])){
                    saveLink($table,$arr['sn'],$frame->fd);
                }
                //执行自动程序
                $res = do_auto_job($arr['data']);
                $ws->push($frame->fd,back_format(['status'=>$res,'type'=>2]));
                break;
            case 3: //接收后台控制数据
                $ws->push(get_fd($table,$arr['sn']),back_format(['status'=>$arr['status'],'type'=>$arr['type']]));
                break;
            case 4: //接收后台设置数据
                $ws->push(get_fd($table,$arr['sn']),back_format(['freq'=>$arr['freq'],'type'=>$arr['type'],'hand_delay'=>$arr['hand_delay']]));
                break;
        }
    }else{
        echo "Message: {$frame->data}\n";
        $pong = new \Swoole\WebSocket\Frame();
        $pong->opcode = WEBSOCKET_OPCODE_PONG;
        $ws->push($frame->fd, $pong);
    }
});

//监听WebSocket连接关闭事件
$ws->on('Close', function ($ws, $fd) use($table) {
echo "client-{$fd} is closed\n";
    $res = $table->get($fd);
    $table->del($res['fd']);
    $table->del($res['sn']);
});

$ws->start();